package com.fanketly.funacg2.ui.screen

import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import com.fanketly.funacg2.R
import com.fanketly.funacg2.data.TAG
import com.fanketly.funacg2.data.model.HistoryModel
import com.fanketly.funacg2.data.model.conventToWork
import com.fanketly.funacg2.ui.components.SwipeToDelete
import com.fanketly.funacg2.ui.screen.destinations.LoginScreenDestination
import com.fanketly.funacg2.ui.theme.FunACG2Theme
import com.fanketly.funacg2.ui.viewmodels.HistoryViewModel
import com.fanketly.funacg2.ui.viewmodels.HomeViewModel
import com.fanketly.funacg2.utils.ToastUtils
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.navigation.DestinationsNavigator

@Destination()
@Composable
fun HistoryScreen(
    homeViewModel: HomeViewModel,
    historyViewModel: HistoryViewModel = hiltViewModel(),
    navigator: DestinationsNavigator,
) {
    val data = historyViewModel.pager.collectAsLazyPagingItems()
    var showDialog by remember {
        mutableStateOf<String?>(null)
    }
    /*   CombinedLoadStates.source 是一种 LoadStates 类型，它具有针对三种不同类型 LoadState 的字段：
       LoadStates.append：适用于在用户当前位置之后获取的项的 LoadState。
       LoadStates.prepend：适用于在用户当前位置之前获取的项的 LoadState。
       LoadStates.refresh：适用于初始加载的 LoadState。

       每个 LoadState 本身可以是下列状态之一：
       LoadState.Loading：正在加载项。
       LoadState.NotLoading：未加载项。
       LoadState.Error：加载时发生错误。*/
    LaunchedEffect(key1 = data.loadState.refresh, block = {
        val refresh = data.loadState.refresh
        if (refresh is LoadState.Error) {
            val localizedMessage = refresh.error.localizedMessage ?: return@LaunchedEffect
            if (localizedMessage.contains("401")) {
                navigator.popBackStack()
                // 跳转到登录页面
                navigator.navigate(LoginScreenDestination)
                ToastUtils.shortToast("请先进行登录")
            } else {
                showDialog = "发生错误，${localizedMessage}"
            }
            Log.i(TAG, "HistoryScreen: $localizedMessage")
        }
    })
    if (showDialog != null) AlertDialog(onDismissRequest = { showDialog = null }, confirmButton = {
        TextButton(onClick = { }) {
            Text(text = stringResource(id = R.string.confirm))
        }
    }, text = { Text(text = showDialog ?: "发生错误，是否重新加载") })
    HistoryContent(data, dismissedToEnd = homeViewModel::openDrawer, onDelete = {
        historyViewModel.delete(it){
            data.refresh()
        }
    }, onClick = {
        homeViewModel.getAudio(it.conventToWork())
    })
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun HistoryContent(
    lazyPagingItems: LazyPagingItems<HistoryModel>,
    dismissedToEnd: () -> Unit,
    onDelete: (Int) -> Unit,
    onClick: (HistoryModel) -> Unit,
) {
    LazyColumn(
        modifier = Modifier
            .fillMaxSize()
            .padding(top = 8.dp),
    ) {
        items(lazyPagingItems.itemCount, key = lazyPagingItems.itemKey { it.id }) {
            val historyEntity = lazyPagingItems[it]
            if (historyEntity != null) SwipeToDelete(
                Modifier.animateItemPlacement(),
                title = historyEntity.title,
                thumbnailCoverUrl = historyEntity.img,
                dismissedToEnd = dismissedToEnd,
                onDelete = { onDelete(historyEntity.id) },
                onClick = { onClick(historyEntity) })
        }
    }
}

@Preview
@Composable
private fun HistoryPreview() {
    FunACG2Theme(true) {
        Surface(Modifier.fillMaxSize()) {
            LinearProgressIndicator(
                modifier = Modifier.fillMaxWidth()
            )
        }
    }
}